/**
 * Created by LeungZ on 2016/9/6.
 */
import delTmp from './form/delete.html';
import delCtrl from './form/delete.ctrl.js';

import addTmp from './form/add.html';
import addCtrl from './form/add.ctrl.js';

class Cluster {
    constructor(list, clusterSrv, $uiModal, ctgNotification, $state) {
        "ngInject";
        this._uiModal = $uiModal;
        this._clusterSrv = clusterSrv;
        this._notification = ctgNotification;
        this._state = $state;

        if (list) {
            this.table = list.list;
            angular.forEach(this.table, elem=> {
                this.getResource(elem);
            })
        }
    }

    getResource(elem) {
        elem.oprLoading = true;
        this._clusterSrv.getClusterInfo(elem.clusterCode).then(data=> {
            elem.resData = data;
        }).catch(data=> {
            this._notification.error('获取容器集群详细数据有误.');
        }).finally(()=> {
            elem.oprLoading = false;
        })
    }

    getList() {
        this.tleLoading = true;
        this._clusterSrv.getClusterList({perPage: 99, currentPage: 1})
            .then(data=> {
                this.table = data.list;
                angular.forEach(this.table, elem=> {
                    this.getResource(elem);
                })
            }).catch(data=> {
                this._notification.error('获取容器集群列表数据有误.');
            }).finally(()=> {
                this.tleLoading = false;
            });
    }

    deleteCluster(elem) {
        this._uiModal.open({
            templateUrl: delTmp,
            controller: delCtrl,
            controllerAs: 'vm',
            windowClass: 'alert-dialog alert-dialog-ctg',
            resolve: {
                clusterName: function () {
                    return elem.clusterName;
                }
            }
        }).result.then(()=> {
                elem.oprLoading = true;
                this._clusterSrv.deleteCluster({id: elem.id}).then(data=> {
                    this.getList();
                    this._notification.success('删除容器集群 ' + elem.clusterName + ' 成功.')
                }).catch(data=> {
                    this._notification.error('删除容器集群 ' + elem.clusterName + ' 失败.');
                }).finally(()=> {
                    elem.oprLoading = false
                })
            });
    }

    addCluster(elem) {
        this._uiModal.open({
            templateUrl: addTmp,
            controller: addCtrl,
            controllerAs: 'vm',
            backdrop: 'static',
            resolve:{
                item:function(){
                    return elem;
                }
            }
        }).result.then(()=> {
                this.getList();
            })
    }
}

export default Cluster;